package com.zreal.generator.codegenerate.database;

import com.zreal.generator.util.Constants;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据源
 * Created 2018/2/6.
 *
 * @author PJ
 */
public class DataSource {

    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private String dbType;

    public static DataSource dataSource;

    private DataSource() {
    }

    public DataSource(String url, String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;
        if (url.contains("oracle")) {
            this.dbType = "oracle";
            this.driverClassName = "oracle.jdbc.driver.OracleDriver";
        } else if (url.contains("sqlserver")) {
            this.dbType = "sqlserver";
            this.driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        } else if (url.contains("mysql")) {
            this.dbType = "mysql";
            this.driverClassName = "com.mysql.jdbc.Driver";
        }
    }

    /**
     * 获取连接
     *
     * @return
     */
    public static Connection getConnection() {
        return getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword(), dataSource.getDriverClassName());
    }

    public static Connection getConnection(String url, String username, String password, String driver) {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(Constants.ERROR_MSG_NOCONNECTION);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("未找到数据库驱动");
        }
        return conn;
    }

    public static DataSource newInstance(String url, String username, String password) {
        if (dataSource == null) {
            dataSource = new DataSource(url, username, password);
        }
        return dataSource;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDbType() {
        return dbType;
    }

    public void setDbType(String dbType) {
        this.dbType = dbType;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
